import { useEffect } from 'react'
import { useSize } from '@/hooks'
import * as echarts from 'echarts'

function useECharts(chartRef, config) {
  let chartInstance = null
  const dom = document.querySelector('body')

  const pageSize = useSize(dom)

  function renderChart() {
    const renderedInstance = echarts.getInstanceByDom(chartRef.current)
    if (renderedInstance) {
      chartInstance = renderedInstance
    } else {
      chartInstance = echarts.init(chartRef.current)
    }
    chartInstance.setOption(config, true)
    chartInstance.resize()
  }

  useEffect(() => {
    if (chartRef.current) {
      renderChart()
    }
  }, [config, pageSize, renderChart, chartRef])

  useEffect(() => {
    return () => {
      chartInstance && chartInstance.dispose()
    }
  }, [chartInstance])

  return
}

export default useECharts
